<template>
  <!-- 维修领料 -->
  <div>
    <!-- 表单 -->
    <FormPanel ref="formTop" :cols="4" :list="filterList" :isSubmitBtn="false"></FormPanel>
    <!-- 表格 -->
    <FilterTable
      ref="table"
      columnsRef="partPartOutboundRepairMaterialsIndex"
      :columns="columns"
      height="450px"
      minHeight="400px"
      :dataSource="dataSource"
      :isMemoryPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="syncTableFun"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="controls">
        <el-button type="primary" :disabled="btnEnable" size="small" @click="showAddWxll">新增</el-button>
        <!-- <el-button type="primary" :disabled="addBtnDisabled" size="small" @click="deleteHandle">删除</el-button> -->
        <el-button type="primary" :disabled="btnEnable" size="small" @click="showEditWxxm">维修项目</el-button>
        <el-button type="primary" :disabled="btnEnable" size="small" :loading="savebtnLoading" @click="saveBtnClick('save')">保存</el-button>
        <el-button type="primary" :disabled="btnEnable || outBtnDisabled" size="small" @click="saveBtnClick('account')">出库</el-button>
        <el-button type="primary" :disabled="btnEnable" size="small" @click="cancelBtnCkick">取消</el-button>
        <el-button type="primary" :disabled="btnEnable" size="small" @click="printShow">打印</el-button>
        <!-- <el-button type="primary" :disabled="btnEnable" size="small" @click="printExit">打印退料单</el-button> -->
      </template>
    </FilterTable>
    <!-- 表单2 -->
    <div style="margin-top:40px">
      <FormPanel ref="form2" :labelWidth="120" :cols="4" :list="filterList2" :isSubmitBtn="false"></FormPanel>
    </div>

    <!-- 打印 -->
    <BasePrint ref="print" :data="printList" destroyOnClose template="templateRepairMaterials" />
    <BasePrint ref="printFu" :data="printList" destroyOnClose template="templateRepairMaterialsExit" />
    <!-- <BasePrint ref="printExit" :showTopIcon="true" :title="'退料单'" :data="printExitList" destroyOnClose template="templateRepairMaterialsExit" /> -->
    <!-- 抽屉组件 或者 弹窗 -->
    <div>
      <!-- 工单查询 -->
      <BaseDialog :visible.sync="isShowGdcx" title="工单查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <WorkSearch :workNo="filterList.find(x => x.fieldName === 'roNo').initialValue" @saveDialog="confirmGdcx" @closeDialog="isShowGdcx = false"></WorkSearch>
      </BaseDialog>
      <!-- 编辑维修领料 -->
      <BaseDialog :visible.sync="isShowEdit" title="编辑维修领料" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <EditPanel :roNo="roNo" :selectRow="wxxlEditRow" :repairTypeCode="repairTypeCode" @confirm="confirmWxll" @cancel="isShowEdit = false"></EditPanel>
      </BaseDialog>
      <BaseDialog :visible.sync="isShowEditBJ" title="编辑维修领料" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <EditPanelBJ :roNo="roNo" :selectRow="wxxlEditRow" :repairTypeCode="repairTypeCode" @confirm="confirmWxll" @cancel="isShowEditBJ = false"></EditPanelBJ>
      </BaseDialog>
      <!-- 维修项目 -->
      <BaseDialog :visible.sync="isShowRepairItem" title="维修项目" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <RepairItem :roNo="roNo" @confirm="confirmWxxm" @cancel="isShowRepairItem = false"></RepairItem>
      </BaseDialog>
      <!-- 新增 -->
      <Drawer :visible.sync="isShowAdd" title="维修领料新增" destroyOnClose width="70%">
        <AddPanel :storageType="storageType" @confirm="confirmAddWxll" @cancel="isShowAdd = false"></AddPanel>
      </Drawer>
      <Drawer :visible.sync="isShowAddBJ" title="维修领料新增" destroyOnClose width="70%">
        <AddPanelBJ :storageType="storageType" @confirm="confirmAddWxllBJ" @cancel="isShowAddBJ = false"></AddPanelBJ>
      </Drawer>
      <!-- 退料 -->
      <BaseDialog :visible.sync="isShowBackPart" title="退料" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <BackPart :roNo="roNo" :partInfo="backPart" :parnArr="tableData" :backPartSaveBtn="backPartSaveBtn" @confirm="confirmTl" @cancel="isShowBackPart = false"></BackPart>
      </BaseDialog>
    </div>
  </div>
</template>

<script>
import { arrayObjDeWeight, notifyAction } from '@/utils/index';
import { state, mutations } from './store';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import Cookies from 'js-cookie';
import { getAppId } from '@/assets/js/auth';
import {
  searchTtRoLabour,
  queryMaintainPicking,
  btnSave,
  account,
  queryPrintDataByRoNoOutStockNo,
  delPartInfo,
  getAllUser,
  exitPart,
  getExitPart
} from '@/api/part/partOutbound/repairMaterials/index.js';
import { addPartInfo, ModifyPartInfo, queryUnitCode, queryPackUnit, getAllModel } from '@/api/part/partInfo';
import { getWxlxSelect, getCheXingSelect, getCangKuSelect, getLingLiaoRenSelect, getShouFeiQuFenSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import util from './common/util';
import WorkSearch from './components/WorkSearch';
import EditPanel from './components/EditPanel';
import EditPanelBJ from './components/EditPanelBJ';
import RepairItem from './components/repairItem';
import AddPanel from './components/AddPanel';
import AddPanelBJ from './components/AddPanelBJ';
import BackPart from './components/BackPart';
import { mapActions } from 'vuex';
import { dealerPrintApi } from '@/api/repair/index.js';
// import { getPartitionList } from '@/api/repair/repair/activitesManage';

export default {
  name: 'part_partOutbound_repairMaterials',
  components: {
    WorkSearch,
    EditPanel,
    RepairItem,
    AddPanel,
    BackPart,
    AddPanelBJ,
    EditPanelBJ
  },
  mixins: [dictionary, authority],
  data() {
    this.deletePartList = []; // 删除的配件列表(af业务使用)
    this.sendBackPartList = []; // 删除的退料列表(af业务员使用)

    return {
      filterList: this.createTopFilterList(),
      filterList2: this.createTopFilterList2(), // 表单2  这里的数据是根据 表格里计算出来的
      columns: this.createTableColumns(),
      allUsers: [], // 存人员数据的
      dataSource: [],
      tableData: [], // table数据
      deleteRows: [], // 要删除的行
      onChangeColumn: [],
      rowSelect: [],
      printExitList: {},
      printTitle: this.getPrintTitle(),
      // 按钮状态控制
      hasRO_NO: false,
      isShowEditBJ: false,
      isShowAddBJ: false,
      addBtnDisabled: false,
      repairItemBtnDisabled: false,
      savebtnLoading: false,
      wxxlEditRow: {},
      backPart: {},
      backPartSaveBtn: false,
      outBtnDisabled: false,

      isShowGdcx: false, // 工单查询 弹窗
      isShowEdit: false, // 维修领料编辑
      isShowRepairItem: false, // 修理项目
      isShowAdd: false, // 新增 面板
      isShowBackPart: false, // 退料
      isShowBackBeforePart: false, // 退前料
      selectRow: null,
      modelData: [], // 所有车型数据
      repairTypeCode: '', // 工单的维修类型
      storageType: '', // 仓库类型 - 用来区分 油车/电车。新增的时候需要带
      printList: {}
    };
  },
  computed: {
    // 工单号
    roNo() {
      return state.roNo;
    },
    btnEnable() {
      return !!!this.hasRO_NO;
    },
    // 是否为af业务
    isAfSys() {
      return getAppId() == 'arcfox';
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    // window.wxll = this;
    this.getAllUser();
    // this.getPartitionList();
    this.getAllModel();
  },
  methods: {
    ...mapActions('app', ['refreshView']),
    async printExit() {
      let roNo = this.roNo;
      let res = await getExitPart({ roNo: roNo });
      if (res.resultCode == 200) {
        this.printExitList = res.data;
        this.$refs.printExit.EXCUTE_PRINT();
      }
    },
    // 获取人员数据接口
    printShow() {
      let outStockNo = '';
      let printFlagZheng = true;
      let printFlagFu = true;
      let roNo = this.roNo;
      if (!this.rowSelect.length) {
        this.$notify.error({ title: '提示信息', message: '请至少选择一条需要打印的数据！！！' });
        return;
      }
      for (let index = 0; index < this.rowSelect.length; index++) {
        const element = this.rowSelect[index];
        printFlagZheng = printFlagZheng && element.PART_QUANTITY > 0;
        printFlagFu = printFlagFu && element.PART_QUANTITY < 0;
      }
      if (!printFlagZheng && !printFlagFu) {
        this.$notify.error({ title: '提示信息', message: '不可同时选择退料和领料数据' });
        return;
      }
      // 取第一个含有发料单号的对象
      for (let index = 0; index < this.rowSelect.length; index++) {
        const element = this.rowSelect[index];
        if (element.OUT_STOCK_NO && element.OUT_STOCK_NO.length) {
          outStockNo = element.OUT_STOCK_NO;
          break;
        }
      }
      if (!outStockNo.length) {
        this.$notify.error({ title: '提示信息', message: '选择的项目中没有发料单号，无法打印！！！' });
        return;
      }
      this.queryPrintDataByRoNoOutStockNo(roNo, outStockNo, printFlagZheng, printFlagFu);
    },
    async queryPrintDataByRoNoOutStockNo(roNo, outStockNo, printFlagZheng, printFlagFu) {
      let res = {};
      if (printFlagZheng) {
        res = await queryPrintDataByRoNoOutStockNo({ roNo, outStockNo });
      }
      if (printFlagFu) {
        res = await getExitPart({ roNo, outStockNo });
      }
      console.log(res.data);
      if (res.resultCode == 200) {
        // 翻译服务顾问和技师
        if (res.data) {
          let serviceAdvisor = this.allUsers.find(item => res.data.SERVICE_ADVISOR == item.value);
          let chiefTechnician = this.allUsers.find(item => res.data.CHIEF_TECHNICIAN == item.value);
          res.data.SERVICE_ADVISOR = serviceAdvisor ? serviceAdvisor.text : res.data.SERVICE_ADVISOR;
          res.data.CHIEF_TECHNICIAN = chiefTechnician ? chiefTechnician.text : res.data.CHIEF_TECHNICIAN;

          let sender = this.allUsers.find(item => res.data.SENDER == item.value);
          let receiver = this.allUsers.find(item => res.data.RECEIVER == item.value);
          res.data.SENDER = sender ? sender.text : res.data.SENDER;
          res.data.RECEIVER = receiver ? receiver.text : res.data.RECEIVER;
        }
        // 翻译发料人和领料人
        if (res.data && res.data.items.length) {
          res.data.items.forEach(x => {
            let sender = this.allUsers.find(item => x.SENDER == item.value);
            let receiver = this.allUsers.find(item => x.RECEIVER == item.value);
            x.SENDER = sender ? sender.text : x.SENDER;
            x.RECEIVER = receiver ? receiver.text : x.RECEIVER;
          });
        }
        this.printList = res.data;
        console.log(this.printList, 'hexj0001');
        if (printFlagZheng) {
          this.$refs.print.EXCUTE_PRINT();
        }
        if (printFlagFu) {
          this.$refs.printFu.EXCUTE_PRINT();
        }
      }
    },
    // 收费区分下拉框
    // async getPartitionList() {
    //   const res = await getPartitionList();
    //   let result = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
    //   this.columns.find(x => x.dataIndex == 'CHARGE_PARTITION_CODE').dictItems = result;
    //   this.columns.find(x => x.dataIndex == 'CHARGE_PARTITION_CODE').filterItems = result;
    // },
    async getAllUser() {
      const res = await getAllUser();
      let salerResult = arrayObjDeWeight(res.data, 'userId');
      let userList = salerResult.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
      this.filterList.find(x => x.fieldName == 'chiefTechnician').itemList = userList;
      this.filterList.find(x => x.fieldName == 'serviceAdvisor').itemList = userList;
      // this.columns.find(x => x.dataIndex === 'SENDER').filterItems = userList;
      // this.columns.find(x => x.dataIndex === 'SENDER').editItems = userList;
      this.columns.find(x => x.dataIndex === 'SENDER').dictItems = userList;
      this.columns.find(x => x.dataIndex === 'RECEIVER').dictItems = userList;
      this.allUsers = userList;
      mutations.setDict_allUser(userList);
    },
    // 获取所有车型
    async getAllModel() {
      const res = await getAllModel();
      let modelData = res.data.map(x => ({
        text: x.MODEL_NAME,
        value: x.MODEL_ID + ''
      }));
      this.modelData = modelData;
      this.filterList.find(x => x.fieldName === 'model').itemList = modelData;
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          initialValue: '',
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.showGdcx}></el-button>;
          },
          onEnter: val => {
            this.showGdcx();
          },
          disabled: false
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          initialValue: '',
          placeholder: '',
          disabled: true
        },

        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '开单日期',
          fieldName: 'roCreateDate',
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '责任技师',
          fieldName: 'chiefTechnician',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '排量',
          fieldName: 'engineDesc',
          initialValue: '',
          placeholder: '',
          disabled: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          width: 60,
          dataIndex: 'xuhao',
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: 120,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delete(props)} disabled={this.rowEditBtnDisabled(props.row)}>
                  删除
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.showEditWxll(props)} disabled={this.rowEditBtnDisabled(props.row)}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.showTl(props)} disabled={this.rowBackBtnDisabled(props.row) || props.row.PART_QUANTITY < 0}>
                  退料
                </el-button>
              </div>
            );
          }
        },
        {
          title: '是否出库',
          sorter: true,
          dataIndex: 'IS_FINISHED',
          editable: false,
          editType: 'select',
          editItems: this.createDictList(1004),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004)
        },
        {
          title: '仓库名称',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dataIndex: 'STORAGE_CODE'
          // render: props => {
          //   return <span>{props.row.STORAGE_NAME}</span>;
          // }
        },
        {
          title: '库位',
          sorter: true,
          dataIndex: 'STORAGE_POSITION_CODE',
          filter: true,
          filterType: 'input'
        },
        {
          title: '主要配件',
          dataIndex: 'IS_MAIN_PART',
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004),
          render: props => {
            return <span>{this.createDictText(props.row.IS_MAIN_PART, 1004)}</span>;
          }
        },
        {
          title: '配件代码',
          sorter: true,
          dataIndex: 'PART_NO',
          showOverflowTooltip: true,
          filter: true,
          width: 150,
          filterType: 'input'
        },
        {
          title: '配件名称',
          sorter: true,
          dataIndex: 'PART_NAME',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          sorter: true,
          dataIndex: 'UNIT_NAME',
          disabled: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '数量',
          sorter: true,
          dataIndex: 'PART_QUANTITY',
          // editable: true,
          // defaultEditable: true,
          // editType: 'number',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '活动编号',
          sorter: true,
          dataIndex: 'ACTIVITY_CODE',
          filter: true,
          filterType: 'input'
        },
        {
          title: '可用库存',
          sorter: true,
          dataIndex: 'USEABLE_STOCK',
          filter: true,
          filterType: 'number'
        },
        {
          title: '锁定数量',
          sorter: true,
          dataIndex: 'LOCKED_QUANTITY',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '单价',
          sorter: true,
          dataIndex: 'PART_SALES_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '金额',
          sorter: true,
          dataIndex: 'PART_SALES_AMOUNT',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '成本价',
        //   sorter: true,
        //   dataIndex: 'PART_SALES_PRICE_NOTAX',
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },

        // {
        //   title: '成本金额',
        //   sorter: true,
        //   dataIndex: 'PART_SALES_AMOUNT_NOTAX',
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },

        {
          title: '收费区分',
          sorter: true,
          dataIndex: 'CHARGE_PARTITION_CODE',
          hidden: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '收费区分',
          sorter: true,
          dataIndex: 'CHARGE_PARTITION_NAME',
          filter: true,
          filterType: 'input'
        },
        {
          title: '发料人',
          sorter: true,
          dataIndex: 'SENDER',
          dictItems: []
        },
        {
          title: '领料人',
          sorter: true,
          dataIndex: 'RECEIVER',
          dictItems: []
        },
        // {
        //   title: '流水号',
        //   sorter: true,
        //   dataIndex: 'BATCH_NO',
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '发料单号',
          sorter: true,
          dataIndex: 'OUT_STOCK_NO',
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修项目名称',
          sorter: true,
          editRequired: true,
          dataIndex: 'LABOUR_CODE',
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },

        {
          title: '替换电池序列号',
          sorter: true,
          dataIndex: 'NEW_BATTERY_SEQUENCE',
          editable: true,
          defaultEditable: true,
          editType: 'text',
          filter: true,
          filterType: 'input'
        },
        {
          title: '老电池序列号',
          sorter: true,
          dataIndex: 'OLD_BATTERY_SEQUENCE',
          editable: true,
          defaultEditable: true,
          editType: 'text',
          filter: true,
          filterType: 'input'
        },
        {
          title: '老电池零件号',
          sorter: true,
          dataIndex: 'OLD_BATTERY_PARTNO',
          editable: true,
          defaultEditable: true,
          editType: 'text',
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createTopFilterList2() {
      return [
        // {
        //   type: 'INPUT',
        //   label: '领料合计金额',
        //   fieldName: 'edtMoney',
        //   precision: 2,
        //   disabled: true
        // },
        {
          type: 'INPUT',
          label: '收费合计金额',
          precision: 2,
          fieldName: 'edtFactMoney',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '领料数量',
          precision: 2,
          fieldName: 'edtCount',
          disabled: true
        }
      ];
    },

    // 删除一行
    delete(props) {
      this.$confirm(`是否确认删除?${this.isAfSys ? '保存过的配件将在重新保存后生效。' : ''}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const row = props.row;
          const index = props.row.$index;
          if (!row.ITEM_ID) {
            // 没有ITEM_ID是还没有保存过的
            this.BaseTable.EXECUTE_DELETE([row]);
            this.$notify.success({ title: '提示信息', message: `删除成功！` });
            return;
          }
          // af业务单独修改为保存时
          if (this.isAfSys) {
            this.deletePartList.push(row);
            this.BaseTable.EXECUTE_DELETE([row]);
            this.$notify.success({ title: '提示信息', message: `删除成功！` });
          } else {
            const res = await delPartInfo(row.ITEM_ID);
            if (res.resultCode == 200) {
              this.$notify.success({ title: '提示信息', message: `删除成功！` });
              let param = { roNo: this.roNo, storageType: this.storageType };
              await this.queryMaintainPicking(param);
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    async initDictData() {
      console.log('查询字典 S');
      // 维修项目
      try {
        const xlxmRes = await searchTtRoLabour({ roNo: state.roNo });
        const xlxmDict = xlxmRes.data.rows.map(x => ({ text: x['LABOUR_NAME'], value: `${x['LABOUR_CODE']}~${x['ITEM_ID']}`, labourItemId: x['ITEM_ID'], labourItemCode: x['LABOUR_CODE'] }));
        mutations.setDict_xlxm(xlxmDict);
      } catch (err) {
        console.log(err, '初始化数据维修项目报错');
      }
      // 是否
      mutations.setDict_isornot([
        { value: 10041001, text: '是' },
        { value: 10041002, text: '否' }
      ]);
      // 领料人
      try {
        const llrRes = await getLingLiaoRenSelect();
        let lightData = arrayObjDeWeight(llrRes.data, 'userId');
        const llrDict = lightData.map(x => ({ text: x['employeeName'], value: x['userId'] }));
        mutations.setDict_llr(llrDict);
      } catch (err) {
        console.log(err, '初始化数据领料人报错');
      }
      // 仓库
      try {
        const ckRes = await getCangKuSelect();
        const ckDict = ckRes.data.map(x => ({ text: x['STORAGE_NAME'], value: x['STORAGE_CODE'] }));
        mutations.setDict_ck(ckDict);
      } catch (err) {
        console.log(err, '初始化数据仓库报错');
      }
      // 维修类型
      try {
        const wxlxRes = await getWxlxSelect();
        const wxlxDict = wxlxRes.data.map(x => ({ text: x['REPAIR_TYPE_NAME'], value: x['REPAIR_TYPE_CODE'] }));
        mutations.setDict_wxlx(wxlxDict);
      } catch (err) {
        console.log(err, '初始化数据维修类型报错');
      }
      // 仓库
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').editItems = state.dict_ck;
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').filterItems = state.dict_ck;
      // 修理项目（维修项目）
      this.columns.find(x => x.dataIndex === 'LABOUR_CODE').filterItems = this.columns.find(x => x.dataIndex === 'LABOUR_CODE').editItems = state.dict_xlxm;
      this.filterList.find(x => x.fieldName === 'repairTypeCode').itemList = state.dict_wxlx;
    },

    // 重新计算table数据
    tableDataCalculateHandler(newVal) {
      // console.log( newVal[0].REAL_AMOUNT, '配件列表数据变化++++++++++++++++++++++11');
      let edtMoney = 0; // 发料合计金额
      let edtFactMoney = 0; // 收费合计金额
      let edtCount = 0; // 发料数量
      let dataList = [...newVal];
      dataList.map(item => {
        let isFinished = item.IS_FINISHED == '10041001'; // 是否入账
        let chargePartitionName = item.CHARGE_PARTITION_NAME; // 收费区分
        let isDiscount = true; // 不可打折
        if (isDiscount) item.DISCOUNT = '1.00'; // 不可打折时折扣率默认为1 可以打折时计算打折价格

        // 计算成本金额
        item.PART_COST_AMOUNT = (item.PART_QUANTITY * item.PART_COST_PRICE).toFixed(2);
        // 计算金额
        item.PART_SALES_AMOUNT = (item.PART_SALES_PRICE * item.PART_QUANTITY).toFixed(2);
        edtMoney += item.PART_SALES_AMOUNT * 1;
        edtCount += item.PART_QUANTITY * 1;

        // 增加实收金额计算for结算：！！！只有自费和保险需要收钱
        if (chargePartitionName == '自费' || chargePartitionName == '保险') {
          this.$set(item, 'REAL_AMOUNT', item.PART_SALES_AMOUNT);
          item.REAL_AMOUNT = item.PART_SALES_AMOUNT * item.DISCOUNT;
        } else {
          this.$set(item, 'REAL_AMOUNT', 0);
          item.REAL_AMOUNT = 0;
        }
        edtFactMoney += item.REAL_AMOUNT * 1;
        // console.log('不计算金额', item.REAL_AMOUNT);
      });

      // this.filterList2.find(x => x.fieldName === 'edtMoney').initialValue = edtMoney.toFixed(2);
      this.filterList2.find(x => x.fieldName === 'edtFactMoney').initialValue = edtFactMoney.toFixed(2);
      this.filterList2.find(x => x.fieldName === 'edtCount').initialValue = edtCount.toFixed(2);
    },

    /** 工单查询 */
    showGdcx() {
      console.log('工单号 点击搜索');
      // 传入工单号给搜索面板 zjw
      this.isShowGdcx = true;
    },
    confirmGdcx([params]) {
      console.log('工单查询确认，', params);
      this.isShowGdcx = false;
      mutations.setRoNo(params['RO_NO']);
      this.hasRO_NO = true;
      // 仓库类型 区分油车/电车
      this.storageType = params['STORAGE_TYPE'];
      // 界面赋值
      const newParams = util.camelCaseObject(params);
      this.filterList.forEach(x => {
        x.initialValue = newParams[x.fieldName];
      });
      // 储存收费区分（增加配件时的默认添加值）
      this.orderChangePartitionCode = params.CHARGE_PARTITION_CODE;
      // 储存维修类型
      this.repairTypeCode = params.REPAIR_TYPE_CODE;

      // 工单必要参数
      this.queryMaintainPicking({ type: '工单带出' });
      this.initDictData();
    },
    // 查询维修领料  （工单带出、保存成功查询、出库成功查询）
    async queryMaintainPicking({ type }) {
      const roNo = this.roNo;
      let param = { roNo: this.roNo, storageType: this.storageType };
      const res = await queryMaintainPicking(param);
      if (res.resultCode != 200) {
        console.log('查询 维修领料 失败');
        return;
      }
      const resArr = res.data;
      console.log('查询 维修领料', { roNo }, res);
      resArr.forEach(item => {
        item['ITEM_UPDATE_STATUS'] = 'U';
        // item['ROW_TYPE'] = type; // 自定义字段  工单带出 保存带出 出库带出
        if (!item.IS_FINISHED) {
          item.IS_FINISHED = 10041002;
        }
      });
      this.dataSource = resArr;
      this.deleteRows = [];
      this.filterList[0].disabled = true;
      this.outBtnDisabled = false; // 保存成功后允许出库
    },
    onRowSelectChange(rows) {
      console.log('选择的行', rows);
      this.rowSelect = rows;
    },

    /** 编辑维修领料 */
    showEditWxll(props) {
      console.log('点击 编辑', props.row);
      this.wxxlEditRow = Object.assign({}, props.row, { $index_edit: props.$index, RECEIVER: Number(props.row.RECEIVER) });
      if (getAppId() == 'beijing') {
        this.isShowEditBJ = true;
      } else {
        this.isShowEdit = true;
      }
    },
    // 编辑点击确定
    confirmWxll(rowData) {
      let row = JSON.parse(JSON.stringify(rowData));
      console.log('编辑确定', row);
      // 单价单独处理
      row.PART_COST_PRICE = Number(row.COST_PRICE);
      row.IS_FLAG = 1;
      state.dict_sfqf.forEach(x => {
        if (x.value == row['CHARGE_PARTITION_CODE']) {
          row['CHARGE_PARTITION_NAME'] = x.text;
          row['CHARGE_PARTITION_CODE'] = x.value;
        }
      });
      // 增加实收金额计算for结算
      if (row['CHARGE_PARTITION_NAME'] == '索赔' || row['CHARGE_PARTITION_NAME'] == '经销商' || row['CHARGE_PARTITION_NAME'] == '免费') {
        // this.$set(item, 'REAL_AMOUNT', 0);
        row.REAL_AMOUNT = 0;
      } else {
        // this.$set(item, 'REAL_AMOUNT', item.PART_SALES_AMOUNT);
        row.REAL_AMOUNT = row.PART_SALES_AMOUNT;
      }
      this.tableData[row.$index_edit] = Object.assign(this.tableData[row.$index_edit], row);
      this.$notify.success({ title: '提示', message: '保存成功！' });
      this.isShowEdit = false;
      this.outBtnDisabled = true;
    },
    /** 维修项目 */
    showEditWxxm() {
      this.isShowRepairItem = true;
    },
    confirmWxxm() {
      this.isShowRepairItem = false;
    },
    /** 新增 */
    showAddWxll() {
      if (getAppId() == 'beijing') {
        this.isShowAddBJ = true;
      } else {
        this.isShowAdd = true;
      }
    },
    confirmAddWxllBJ(rows) {
      console.log('新增', rows);
      rows.forEach(row => {
        row['ITEM_UPDATE_STATUS'] = 'A'; // A新增 U更新
        // 成本单价
        row.PART_COST_PRICE = Number(row.COST_PRICE);
        // 含税采购价
        row.TAX_PURCHASE_PRICE = row.PLAN_PRICE;
        // 含税采购金额
        row.TAX_PURCHASE_AMOUNT = (row.TAX_PURCHASE_PRICE * row.PART_QUANTITY).toFixed(2);
        /** 处理数据 S */
        // 是否入账 默认否
        row.IS_FINISHED = 10041002;
        row.DISCOUNT = 1;

        row.RECEIVER = Cookies.get('userId');
        // 设置默认收费区分
        // row.CHARGE_PARTITION_CODE = this.orderChangePartitionCode || 'Z';
        // row.CHARGE_PARTITION_NAME = this.state.dict_sfqf.find(item => item.value == row.CHARGE_PARTITION_CODE).text || '自费类';
        /** 处理数据 E */
        console.log(row, 'rowData');
      });
      // 判断是否存在
      // const flag = this.tableData.find(item => {
      //   const isHave = item['PART_NO'] === row['PART_NO'] && item['STORAGE_CODE'] === row['STORAGE_CODE'];
      //   const isRuZhang = item['IS_FINISHED'] == '10041001';
      //   return isHave && !isRuZhang;
      // });
      // if (flag) {
      //   console.log('配件已存在');
      //   this.$notify({ title: '警告', message: '配件已存在', type: 'warning' });
      //   return;
      // }

      // row.CHARGE_PARTITION_CODE = '';
      // row.CHARGE_PARTITION_NAME = '';
      // row.PRICE_TYPE = '';
      // row.PART_SALES_PRICE = '';
      // row.PART_SALES_AMOUNT = '';
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(rows);
      this.$notify({ title: '提示', message: '新增成功', type: 'success' });
      this.outBtnDisabled = true;
    },
    confirmAddWxll(row) {
      console.log('新增', row);
      // 判断是否存在
      // const flag = this.tableData.find(item => {
      //   const isHave = item['PART_NO'] === row['PART_NO'] && item['STORAGE_CODE'] === row['STORAGE_CODE'];
      //   const isRuZhang = item['IS_FINISHED'] == '10041001';
      //   return isHave && !isRuZhang;
      // });
      // if (flag) {
      //   console.log('配件已存在');
      //   this.$notify({ title: '警告', message: '配件已存在', type: 'warning' });
      //   return;
      // }
      row['ITEM_UPDATE_STATUS'] = 'A'; // A新增 U更新
      // 成本单价
      row.PART_COST_PRICE = Number(row.COST_PRICE);
      // 含税采购价
      row.TAX_PURCHASE_PRICE = row.PLAN_PRICE;
      // 含税采购金额
      row.TAX_PURCHASE_AMOUNT = (row.TAX_PURCHASE_PRICE * row.PART_QUANTITY).toFixed(2);
      /** 处理数据 S */
      // 是否入账 默认否
      row.IS_FINISHED = 10041002;
      row.DISCOUNT = 1;

      row.RECEIVER = Cookies.get('userId');
      // 设置默认收费区分
      // row.CHARGE_PARTITION_CODE = this.orderChangePartitionCode || 'Z';
      // row.CHARGE_PARTITION_NAME = this.state.dict_sfqf.find(item => item.value == row.CHARGE_PARTITION_CODE).text || '自费类';
      /** 处理数据 E */
      console.log(row, 'rowData');
      // row.CHARGE_PARTITION_CODE = '';
      // row.CHARGE_PARTITION_NAME = '';
      // row.PRICE_TYPE = '';
      // row.PART_SALES_PRICE = '';
      // row.PART_SALES_AMOUNT = '';
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(row);
      this.$notify({ title: '提示', message: '新增成功', type: 'success' });
      this.outBtnDisabled = true;
    },
    /** 退料 */
    showTl(props) {
      this.backPart = props.row;
      this.isShowBackPart = true;
    },
    // 先走保存 - 再走出库就完成了退料
    async confirmTl(backRow) {
      this.backPartSaveBtn = true;
      const num = backRow['PART_QUANTITY'];
      const part_no = this.backPart['PART_NO'];
      // 计算可退料数量
      const partArr = this.tableData.filter(item => {
        // 是否入账
        const isStorage = item.STORAGE_CODE == backRow.STORAGE_CODE;
        const isPart = item.PART_NO == backRow.PART_NO;
        // const isFinished = item['IS_FINISHED'] == '10041001';
        const isAvailable = isStorage && isPart;
        return isAvailable || (item['TL_FROM'] && isPart);
      });
      console.log('统计的', partArr);
      // 判断退料数量是否合法
      let numAvailable = 0;
      partArr.forEach(item => {
        numAvailable += Number(item['PART_QUANTITY']);
      });
      numAvailable = Number(numAvailable.toFixed(2));
      console.log('计算可退料数量', partArr, { num, numAvailable });
      if (num > numAvailable) {
        // 退料数量大于可退数
        this.$notify({
          title: '警告',
          message: '退料数量不能大于领料数量',
          type: 'warning'
        });
        this.backPartSaveBtn = false;
        return;
      }
      // 退料合法 继续走下面
      const row = Object.assign({}, this.backPart);
      row._uid = null;
      // 数量 金额 不含税金额 成本金额
      row['PART_QUANTITY'] = -num;
      row['PART_SALES_AMOUNT'] = -num * Number(row['PART_SALES_AMOUNT'] || 0);
      row['PART_SALES_AMOUNT_NOTAX'] = -num * Number(row['PART_SALES_AMOUNT_NOTAX'] || 0);
      row['PART_COST_AMOUNT'] = -num * Number(row['PART_COST_AMOUNT'] || 0);
      row['ITEM_UPDATE_STATUS'] = this.isAfSys ? null : 'A';
      row['IS_FINISHED'] = 10041002;
      row['TL_FROM'] = true;
      let aData = [];
      aData.push(row);
      for (const item of this.tableData) {
        aData.push(item);
      }
      const params = {};
      this.filterList.forEach((item, i) => {
        params[item.fieldName] = item.initialValue;
      });
      this.filterList2.forEach((item, i) => {
        params[item.fieldName] = item.initialValue;
      });
      params.maintainPickingTbl = aData.map(item => {
        const row1 = util.camelCaseObject(item);
        if (row1.labourCode) {
          // 开启配件关联维修项目开关后，前台需要向后台传配件所关联的维修项目的labourItemId
          const labourItem = state.dict_xlxm.find(x => x.value == row1.labourCode);
          if (labourItem) {
            row1.labourItemId = labourItem.labourItemId;
          }
        }
        return row1;
      });
      params.license = this.filterList.find(x => x.fieldName === 'license').initialValue;
      console.log('点击保存 参数', params);
      if (this.isAfSys) {
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(row);
        this.sendBackPartList.push(util.camelCaseObject(row));
        console.log(this.sendBackPartList, 'hexj001');
      } else {
        const res = await exitPart(params);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示', message: '退料成功' });
          // 刷新
          this.refeshPageData();
        }
      }
      // const res = await btnSave(params);
      // if (res.resultCode == 200) {
      //   const roNo = this.roNo;
      //   let param = { roNo: this.roNo, storageType: this.storageType };
      //   const res = await queryMaintainPicking(param);
      //   if (res.resultCode != 200) {
      //     console.log('查询 维修领料 失败');
      //     this.backPartSaveBtn = false;
      //     return;
      //   }
      //   const resArr = res.data;
      //   /** 处理数据 E */
      //   let resData = resArr.find(x => x.STORAGE_CODE == row.STORAGE_CODE && x.PART_NO == row.PART_NO && x.IS_FINISHED == 10041002 && x.PART_QUANTITY < 0);
      //   const _rowSelect = [util.camelCaseObject(resData)];
      //   params.maintainPickingTbl = _rowSelect;
      //   console.log('出库', 'lt2', params);
      //   {
      //     const res = await account(params);
      //     if (res.resultCode == 200) {
      //       this.$notify.success({ title: '提示', message: '退料成功' });
      //       // 刷新
      //       let param = { roNo: this.roNo, storageType: this.storageType };

      //       await this.queryMaintainPicking(param);
      //     }
      //   }
      // }
      this.isShowBackPart = false;
      this.backPartSaveBtn = false;
    },
    /** 列表按钮是否可用 */
    rowDeleteBtnDisabled(row) {
      // 工单带出 ，是否入账：是，“删除”按钮置灰不可用
      // 工单带出 ，是否入账：否，“删除”按钮高亮可用
      let flag = false;
      const type = row['ROW_TYPE'];
      const isFinished = row['IS_FINISHED'] == '10041001';
      if (isFinished) {
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    },
    // 操作按钮是否可用 - 针对 删除和编辑
    rowEditBtnDisabled(row) {
      // 退料的不可编辑
      let flag = false;
      const num = Number(row['PART_QUANTITY']);
      if (num < 0) {
        flag = true;
      } else {
        if (row['IS_FINISHED'] == '10041001') {
          flag = true;
        } else {
          flag = false;
        }
      }
      return flag;
    },
    rowBackBtnDisabled(row) {
      // 已入账才可退料
      let flag = true;
      const isFinished = row['IS_FINISHED'] == '10041001';
      if (isFinished) {
        flag = false;
      }
      return flag;
    },
    // 保存按钮
    async saveBtnClick(type) {
      console.log('type', type);
      const params = {};
      this.filterList.forEach((item, i) => {
        params[item.fieldName] = item.initialValue;
      });
      this.filterList2.forEach((item, i) => {
        params[item.fieldName] = item.initialValue;
      });
      let tableError = this.$refs.table.GET_REQUIRED_ERROR();
      if (tableError) return this.$notify.error({ title: '提示信息', message: tableError.message });
      params.license = this.filterList.find(x => x.fieldName === 'license').initialValue;
      console.log('点击保存 参数', params);
      // return
      if (type == 'save') {
        console.log('保存', params);
        params.maintainPickingTbl = this.tableData.map(item => {
          return util.camelCaseObject(item);
        });
        // 删除的配件
        params.delTbl = this.deletePartList.map(item => item.ITEM_ID);
        params.maintainPickingTblTl = this.sendBackPartList.map(item => {
          item.oldItemId = item.itemId;
          return item;
        });

        if (this.savebtnLoading) return;
        this.savebtnLoading = true;
        try {
          const res = await btnSave(params);
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示', message: '保存成功' });
            await this.refeshPageData();
            this.outBtnDisabled = false; // 保存成功后允许出库
          }
          this.savebtnLoading = false;
        } catch (err) {
          this.savebtnLoading = false;
          this.$notify.error({ title: '提示', message: '保存失败' });
          this.refeshPageData();
        }
      } else if (type == 'account') {
        // 已勾选才出库
        if (this.rowSelect.length == 0) {
          return this.$notify.warning({ title: '警告', message: '请选择要出库的配件' });
        }
        console.log(this.rowSelect, 'this.rowSelect');
        for (const item of this.rowSelect) {
          if (!item.ITEM_ID) {
            return this.$notify.warning({ title: '警告', message: '新增未保存配件无法出库' });
          }
          if (item.IS_FINISHED == 10041001) {
            return this.$notify.warning({ title: '警告', message: '选中的配件包含已出库配件' });
          }
          if (!item.PRICE_TYPE || item.PRICE_TYPE == '') {
            return this.$notify.warning({ title: '警告', message: '选中的配件未维护价格' });
          }
        }
        const _rowSelect = this.rowSelect.map(item => {
          return util.camelCaseObject(item);
        });
        params.maintainPickingTbl = _rowSelect;
        console.log('出库', params);
        // TODO:权限控制
        const res = await account(params);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示', message: '出库成功' });
          // 刷新
          this.refeshPageData();
        }
      }
    },
    // 重新查询
    async refeshPageData() {
      let param = { roNo: this.roNo, storageType: this.storageType };
      await this.queryMaintainPicking(param);
      this.deletePartList = [];
      this.sendBackPartList = [];
    },
    // 取消 - 重新选择工单
    cancelBtnCkick() {
      console.log('取消');

      this.$refs.formTop.RESET_FORM();
      this.filterList.find(x => x.fieldName === 'roNo').disabled = false;
      this.hasRO_NO = false;
      this.outBtnDisabled = false;
      this.dataSource = [];
      mutations.setRoNo('');
      this.storageType = '';
      this.orderChangePartitionCode = '';
      this.repairTypeCode = '';

      this.deletePartList = [];
      this.sendBackPartList = [];

      // this.$refs.table.
      // this.refreshView({ path: '/part/partOutbound/repairMaterials' });
    },
    // 判断配件是否已存在
    partIsHave(partNo) {
      const isHave = this.tableData.find(item => {
        return item['PART_NO'] == partNo;
      });
      return isHave;
    },
    getPrintTitle() {
      let appId = getAppId();
      if (appId == 'beijing') {
        return 'BEIJING汽车配件领料单';
      } else {
        return '蓝谷极狐配件领料单';
      }
    },
    syncTableFun(val) {
      this.tableData = val;
      this.tableDataCalculateHandler(val);
      console.log(val, 'table列表项数据变化');
      for (const obj of val) {
        obj.IS_FLAG = 1;
        if (obj.CHARGE_PARTITION_NAME.length === 1) {
          obj.CHARGE_PARTITION_CODE = obj.CHARGE_PARTITION_NAME;
        }
        if (obj.IS_FINISHED == 10041001 || Number(obj.PART_QUANTITY) < 0) {
          this.BaseTable.SET_CELL_DISABLED(obj, 'LABOUR_CODE', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'NEW_BATTERY_SEQUENCE', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'OLD_BATTERY_SEQUENCE', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'OLD_BATTERY_PARTNO', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'IS_DISCOUNT', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'DISCOUNT', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'PART_QUANTITY', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'PART_SALES_PRICE', true);
          this.BaseTable.SET_CELL_DISABLED(obj, 'CHARGE_PARTITION_NAME', true);
        }
      }
      // this.outBtnDisabled = true;
      // this.dataSource = val;
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJCK'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
    }
  }
};
</script>

<style lang="less" scoped>
.btn-group-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
}
</style>
